// pages/friends/friends.js
var util = require('../../utils/util.js')
var http = require('../../utils/http.js')

// 在页面中定义激励视频广告
let videoAd = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    fiveTimes: false,
    canSuccess: false,
    helpCan: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    var that = this;
    var bargainId = options.bargainId;
    var userId = options.userId;
    that.setData({
      bargainId,
      userId
    })
    // 在页面onLoad回调事件中创建激励视频广告实例
    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-96e23d22adce41d3'
      })
      videoAd.onLoad(() => {})
      videoAd.onError((err) => {})
      videoAd.onClose((res) => {
        if (res && res.isEnded || res === undefined) {
          console.log("我看完视频了");
          that.helpCanReward();
        } else {
          // 播放中途退出，进行提示
          wx.showToast({
            title: '观看广告时间不足，无法获得奖励',
            icon: "none",
            duration: 2000
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  back:function () {
    wx.navigateBack({
      delta: 1
    })
  },
  //帮忙砍价的奖励
  helpCanReward: function() {
    var that = this;
    const data = {
      bargainId: that.data.bargainId,
      userId: that.data.userId
    }
    http.helpBargain(data).then( res => {
      var toastMoney = res.money / 10000;
      that.setData({
        fiveTimes: true,
        helpCan: false,
        toastMoney
      })
      setTimeout(() => {
        that.setData({
          fiveTimes: false,
        })
      },1500)
    }, err => {
      wx.showModal({
        content: err,
        showCancel: false,
      })
    })
  },
  // 帮砍价
  helpCan: function() {
    var that = this;
    // 用户触发广告后，显示激励视频广告
    if (videoAd) {
      videoAd.show().catch(() => {
        // 失败重试
        videoAd.load()
          .then(() => videoAd.show())
          .catch(err => {
            console.log('激励视频 广告显示失败')
          })
      })
    }
    
  },
  onShareAppMessage: function() {
    var that = this;
    var bargainId = that.data.bargainId;
    var userId = wx.getStorageSync("userId");
    return {
      title: '好友邀请你砍一刀，免费领取100块钱红包？',
      path: 'pages/friends/friends?userId=' + userId & 'bargainId=' + bargainId,
    }
  },
  // 我也要免费拿和回到首页，跳转到discount页面
  freeToo: function() {
    wx.navigateTo({
      url: '/pages/discount/discount'
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
})